package com.softeem.ssm2.service.impl;

import com.softeem.ssm2.dao.UserMapper;
import com.softeem.ssm2.dto.Result;
import com.softeem.ssm2.entity.User;
import com.softeem.ssm2.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author mrchai
 * @Date 2019/10/16 15:12
 */
@Transactional
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ModelAndView addUser(User user) {
        ModelAndView mv = new ModelAndView();
        //1.先查询当前用户是否已存在
        User u = userMapper.selectByUsername(user.getUsername());
        if(u != null){
            mv.addObject("msg","该账号已存在");
            mv.addObject("code",-1);
            mv.setViewName("reg");
        }else{
            int i = userMapper.insert(user);
            mv.addObject("msg",i>0?"注册成功":"注册失败");
            mv.addObject("code",i);
            mv.setViewName("main");
        }
        return mv;
    }

    @Override
    public Result queryByUser(User user) {
        Result r = new Result();
        //根据controller传递过来的用户的username查询
        User u = userMapper.selectByUsername(user.getUsername());
        if(u != null){
            if(u.getPassword().equals(user.getPassword())){
                if(u.getStatus() == 1) {
                    r.setMsg("登录成功");
                    r.setCode(1);
                    r.setData(u);
                    r.setSuccess(true);
                }else{
                    r.setMsg("账号被禁用");
                    r.setCode(-2);
                }
            }else{
                r.setMsg("密码错误");
                r.setCode(0);
            }
        }else{
            r.setCode(-1);
            r.setMsg("用户不存在");
        }
        return r;
    }
}
